<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2019 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2019-06-02
 * Time: 10:10
 */

namespace App\Library\Mall\Item;


use App\Exceptions\ApiRequestException;
use App\Models\Item;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait ItemCollectManagers
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiRequestException
     */
    public function add(Request $request)
    {
        $itemid = $request->input('itemid', 0);
        if ($item = Item::find($itemid)) {
            $collect = Auth::user()->collectedItems()->where('itemid', $itemid)->first();
            if (!$collect) {
                $collect = Auth::user()->collectedItems()
                    ->create([
                        'itemid' => $itemid,
                        'title' => $item->title,
                        'image' => $item->thumb,
                        'price' => $item->price
                    ]);
            }
            return ajaxReturn(['collect' => $collect]);
        } else {
            throw new ApiRequestException(trans('item.this item has been removed'));
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');
        Auth::user()->collectedItems()->where('id', $id)->delete();
        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get(Request $request)
    {
        $itemid = $request->input('itemid');
        $collect = Auth::user()->collectedItems()->with('item')->where('itemid', $itemid)->first();
        return ajaxReturn(['collect' => $collect]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    protected function batchgetCollects(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 20);
        $q = $request->input('q');

        $items = Auth::user()->collectedItems()->when($q, function (Builder $builder) use ($q) {
            return $builder->where('title', 'LIKE', "%$q%");
        })->offset($offset)->take($count)->get();

        return $items;
    }
}
